package com.xja.warehouse.exception;

import com.xja.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

@RestControllerAdvice(basePackages = "com.xja.warehouse.controller")
public class WarehouseExceptionControllerAdvice {
    // ExceptionHandler指定处理哪种异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> fieldError.getField()
                , fieldError -> fieldError.getDefaultMessage()));
        return R.error(400,"参数不合规").put("data",map);
    }
}
